{ config, lib, ... }:
with lib;
let
  cfg = config.roles.server.adguardhome;
in {
  options.roles.server.adguardhome = {
    enable = mkOption {
      default = false;
      type = types.bool;
    };
    domain = mkOption {
      default = config.roles.server.domain;
      type = types.str;
    };
  };

  config = mkIf cfg.enable {
    roles.server.nginx.enable = mkForce true;

    systemd.services.adguardhome.serviceConfig.SupplementaryGroups = [ "acme" ];

    networking.firewall = {
      allowedTCPPorts = [ 853 ];
      allowedUDPPorts = [ 53 ];
    };

    services = {
      adguardhome.enable = true;

      nginx = {
        upstreams.adguardhome.servers = { "127.0.0.1:${toString config.services.adguardhome.port}" = {}; };
        virtualHosts."dns.${cfg.domain}" = {
          forceSSL = true;
          useACMEHost = cfg.domain;
          locations = {
            "/".proxyPass = "http://adguardhome";
            "/dns-query".proxyPass = "https://127.0.0.1:7443";
          };
        };
      };
    };
  };
}
